About 1998 letters
About 10 minutes
In Python, regular expressions are used via the re module. Since regular expressions have their own escape syntax, it’s common to use Python raw strings to avoid double escaping.
Function | Description | Example |
---|---|---|
match | Checks if the string matches the pattern from the beginning | See below |
search | Searches for a substring matching the pattern | See below |
sub | Replaces substrings that match the pattern | See below |
split | Splits string using substrings that match the pattern | See below |
compile | Compiles a pattern for reuse | See below |
import re
# Validate email format
email_pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
if re.match(email_pattern, "user@example.com"):
print("Valid email")
import re
text = "Order ID: 12345, Date: 2023-08-15"
match = re.search(r'Order ID: (\d+), Date: (\d{4}-\d{2}-\d{2})', text)
if match:
print(0, match.group(0))
print(1, match.group(1))
print(2, match.group(2))
import re
text = "Username: user Password: 123456"
hidden = re.sub(r'\d{6}', '******', text)
print(hidden)
import re
data = "Apple, Banana, Orange, Grape"
fruits = re.split(r',\s*', data) # Split by comma, allowing optional space after
print(fruits) # Output: ['Apple', 'Banana', 'Orange', 'Grape']
Compiling a pattern improves efficiency when used multiple times.
import re
# Compile email pattern
email_pattern = re.compile(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$')
if email_pattern.match("user@example.com"):
print("Valid email")
Created in 5/15/2025
Updated in 5/21/2025